package hit.dao.database;

import hit.core.HomeInventoryTracker;
import hit.dao.SettingsDAO;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * A DAO that handles all Item operations by using serialization. It actually does
 * not do anything, because serialization is only done on load and close.
 */
public class DBSettingsDAO implements SettingsDAO{
	
	DatabaseDAO databaseDAO;
	
	public DBSettingsDAO(DatabaseDAO databaseDAO){
		this.databaseDAO = databaseDAO;
	}

	@Override
	public void GetAll(HomeInventoryTracker hit) throws SQLException {
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		//query the database to get all the objects in the database
		try {
			try {
				//have the individual daos initialize their prepared statement
				String sql = "SELECT * FROM settings LIMIT 1";
				stmt = databaseDAO.GetConnection().prepareStatement(sql);
			    
				//execute the query and hand the result set to the child class to process
			    rs = stmt.executeQuery();
			    
			    hit.SetRemovedReportLastRun(rs.getDate(1));
			    hit.SetNextItemID(rs.getInt(2));
			    
			}
			finally {//close up resources
			    if (stmt != null) 
			    	stmt.close();
			    if (rs != null)
			    	rs.close();
			}
		}
		catch (SQLException e) {
		    e.printStackTrace();
		}
	}

	@Override
	public void Update(HomeInventoryTracker hit) throws SQLException {
		PreparedStatement stmt = null;
		
		try {
			try {
				//have the individual daos initialize their prepared statement
				String sql = "UPDATE settings SET nmonth_last_run = ?, next_item_id = ?";
				stmt = databaseDAO.GetConnection().prepareStatement(sql);
				if (hit.GetRemovedReportLastRun() == null)
					stmt.setDate(1, null);
				else
					stmt.setDate(1, new Date(hit.GetRemovedReportLastRun().getTime()));
				stmt.setInt(2, hit.GetNextItemID());
			    stmt.executeUpdate();
			    
			}
			finally {//close up resources
			    if (stmt != null) 
			    	stmt.close();
			}
		}
		catch (SQLException e) {
		    e.printStackTrace();
		}
	}

}
